<?php

  namespace app\index\controller;
  use app\index\Controller;
  use think\Db;
  use think\Validate;
  use think\Config;

  /**
   * @title 培训（模块07）
   * @description 接口说明
   * @group 培训
   * @header name:model_id   default:07 desc:模块id
   * @groupremark 已使用错误码：1070001 1070002 1070003 1070004 1070005 1070006 1070007
   */
   class Train extends Controller{

     /**
      * @title 培训课程信息
      * @description 接口说明
      * @author 李锐志
      * @url /index/train/index
      * @param name:token type:string require:1  other: desc:token
      * @param name:user_id type:int require:1  other: desc:user_id
      * @param name:training_materials_id type:string require:1  other: desc:培训资料id
      * @method ~
      * @return error_id: 1070001 校验错误
      * @return error_id: 1070002 获取失败
      * @return data:课程信息@!
      * @data id:课程id title:标题 video_title:视频标题 video_url:视频路径 video_length:视频长度 create_time:添加时间 update_time:更新时间 content_title:内容标题 content:内容 view_num:浏览数量 rank_id:适合看的司机等级
      */

      public function index(){
        //获取数据
        $data = input();

        //验证规则
        $validate = new Validate([
          ['token','require','缺少token'],
          ['user_id','require','未指定用户'],
          ['training_materials_id','require','缺少培训资料id'],
        ]);

        //验证数据
        if(!$validate->check($data)){
          $msg['error_id']="1070001";
          $msg['message']=$validate->getError();
          return $this->error($msg);
        }

        //通过培训资料id到training_meterials表中获取数据
        $result = Db::name('training_materials') -> where('id',$data['training_materials_id']) -> find();
        $update['view_num'] = $result['view_num']+1;
        Db::name('training_materials') -> where('id',$data['training_materials_id']) -> update($update);
        $view['training_materials_id']=$data['training_materials_id'];
          $view['user_id']=$data['user_id'];
          $view['view_end']=NOW_TIME;
          $view['create_time']=NOW_TIME;
          $view['update_time']=NOW_TIME;
        $old_training_materials_view=Db::name('training_materials_view')->where(array('user_id'=>$data['user_id'],'training_materials_id'=>$data['training_materials_id']))->find();
        if(!$old_training_materials_view){
        	Db::name('training_materials_view')->insert($view);
        }

          if($result['video_img_id']){
              $result['video_img_url']=get_host().get_default_img($result['video_img_id'],true);
          }else{
              $result['video_img_url']="/upload/img/5b0ab1a7bbd7ae17.png";
          }
        $msg['data'] = $result;
        if($result==true){
          $msg['message'] = '获取成功';
          return $this->success($msg);
        }else{
          $msg['message'] = '获取失败';
          $msg['error_id'] = '1070002';
          return $this->error($msg);
        }

      }

      /**
       * @title 培训课程列表
       * @description 接口说明
       * @author 李锐志
       * @url /index/train/trainlist
       * @param name:token type:string require:1  other: desc:token
       * @param name:rank_id type:string require:1  other: desc:司机等级
       * @method ~
       * @return error_id: 1070003 校验错误
       * @return error_id: 1070004 获取失败
       * @return error_id: 1070005 司机等级不存在
       * @return list:课程列表@
       * @list id:课程id title:标题 video_title:视频标题 video_url:视频路径 video_length:视频长度 create_time:添加时间 update_time:更新时间 content_title:内容标题 content:内容 view_num:浏览数量 rank_id:适合看的司机等级
       */
      public function trainlist(){

          //获取数据
          $data = input();

          //验证规则
          $validate = new Validate([
            ['token','require','缺少token'],
            ['rank_id','require','缺少rank_id'],
          ]);

          //验证数据
          if(!$validate->check($data)){
            $msg['error_id']="1070003";
            $msg['message']=$validate->getError();
            return $this->error($msg);
          }
          if($data['rank_id']==null){
            $msg['message'] = '司机等级不存在';
            $msg['error_id'] = '1070005';
            return $this->error($msg);
          }
          $result = Db::name('training_materials') -> where('rank_id',$data['rank_id']) -> select();
          foreach ($result as $key=>$value){
              if($value['video_img_id']){
                  $value['video_img_url']=get_host().get_default_img($value['video_img_id'],true);
              }else{
                  $value['video_img_url']="/upload/img/5b0ab1a7bbd7ae17.png";
              }
              $result[$key]=$value;
          }
          $msg['list'] = $result;
          if($result==true){
            $msg['message'] = '成功';
            return $this->success($msg);
          }else{
            $msg['message'] = '失败';
            $msg['error_id'] = '1070004';
            return $this->error($msg);
          }
      }

       /**
        * @title 培训认证等级信息
        * @description 接口说明
        * @author 陈庆锋
        * @url /index/train/trainValidate

        * @param name:token type:string require:1  other: desc:
        * @param name:user_id type:string require:1  other: desc:

        * @return data:培训认证@!
        * @data rank_id:等级id rank_name:等级名称 order_num:司机完成的订单数
        * @data  min_score:等级考试需要的最低分
        * @data  training_materials_view_msg:该等级的所有培训课程完成情况
        * @data  training_materials_view_status:该等级的所有培训课程完成情况的状态码,1为完成,0为未完成
        * @data  training_materials:培训的课程
        * @data  score:司机等级考试的分数 user_paper_exam_msg:司机等级考试的信息
        * @data  user_paper_exam_status:司机等级考试的信息状态码,1为完成,0为未完成
        * @data  user_paper_id:试卷的id号
        * @data  order_num_complete_msg:完成的订单量的情况
        * @data  order_num_complete_status:完成的订单量的情况的状态码,1为完成,0为未完成
        * @method  ~
        */
        function trainValidate(){

            //获取参数
            $data = input();

            //验证规则
            $validate = new Validate([
                ['token','require','缺少token'],
                ['user_id','require','缺少user_id'],
            ]);

            //验证数据
            if(!$validate->check($data)){
                $msg['error_id']="1070006";
                $msg['message']=$validate->getError();
                return $this->error($msg);
            }

            //获取登录用户的id
            $user_id = $data['user_id'];

            //
            $driver_train_list = get_ranks();
            //得到各个等级认证的课程
            for($i=0;$i<count($driver_train_list);$i++){
                $course = Db::name('training_materials')
                    ->field('id training_materials_id')
                    ->where('rank_id='.$driver_train_list[$i]['id'])
                    ->select();
                //判断该司机是否观看完该等级的所有课程
                $is_see = Db::name('training_materials_view')
                    ->field('training_materials_id')
                    ->where('user_id='.$user_id)
                    ->select();
                $flag = 1;
                foreach ($course as $k=>$vcourse) {
                    if (in_array($vcourse, $is_see)) {
                        $course[$k]['this_training_materials_view_msg'] = '这门培训课程看完了';
                        $course[$k]['this_training_materials_view_status'] = '1';
                        continue;
                    }else {
                        $flag = 0;
                        $course[$k]['this_training_materials_view_msg'] = '这门培训课程没看完';
                        $course[$k]['this_training_materials_view_status'] = '0';
                    }
                }
                if($flag){
                    $driver_train_list[$i]['training_materials_view_msg'] = '培训课程看完了';
                    $driver_train_list[$i]['training_materials_view_status'] = 1;
                }else{
                    $driver_train_list[$i]['training_materials_view_msg'] = '培训课程没看完';
                    $driver_train_list[$i]['training_materials_view_status'] = 0;

                }
                $driver_train_list[$i]['training_materials'] = $course;

            }

            //获取司机的等级
            $driver = DB::name('driver')->where('user_id','=',$user_id)->find();
            $driver_rank = Db::name('driver_rank')->order('order_num','desc')->select();

            $driver_info = [];
            if ($driver){
                $driver_info['user_id'] = $driver['user_id'];
                $driver_info['order_num'] = $driver['order_num'];
                $driver_info['driver_rank_id'] = $driver['driver_rank_id'];
                //司机等级列表
                $driver_rank_count = count($driver_rank);
                for ($i = 0; $i < $driver_rank_count; $i++){
                    if ($driver_rank[$i]['id'] == $driver['driver_rank_id']){

                        $driver_info['rank_name'] = $driver_rank[$i]['name'];

                        $driver_info['min_order_num'] = $driver_rank[$i]['order_num'];
                        $driver_info['max_order_num'] = ($i==0?99999:$driver_rank[$i-1]['order_num']);

                        $driver_info['test_status'] = 0;
                        $driver_info['course'] = $driver_train_list[(count($driver_train_list)-1)- $i];
                        //判断当前订单数是否超过下一等级订单数
                        if ($i>0){
                            $driver_info['course'] = $driver_train_list[count($driver_train_list) - $i];
                            if($driver_rank[$i-1]['order_num'] <= $driver['order_num']){
                                $driver_info['test_status'] = 1;
                                //获取下一等级的课程
                                foreach ($driver_info['course']['training_materials'] as $k=>$v) {
                                    if($v['this_training_materials_view_status']!='1'){
                                        $driver_info['test_status'] = 0;
                                        break;
                                    }
                                }
                            }
                        }
                        break;
                    }else if($i == ($driver_rank_count-1) && empty($driver['driver_rank_id'])){
                    //新手无等级的情况下
                        $driver_info['rank_name'] = $driver_rank[$i]['name'];
                        $driver_info['min_order_num'] = 0;
                        $driver_info['max_order_num'] = $driver_rank[$i]['order_num'];
                        $driver_info['test_status'] = 0;
                        $driver_info['course'] = $driver_train_list[(count($driver_train_list)-1)-$i];
                        //判断按钮是否能点击（test_status）
                        if (!empty($driver_info['course']) && !empty($driver_info['course']['training_materials'])){
                            $driver_info['test_status'] = 1;
                            for ($x = 0; $x <count($driver_info['course']['training_materials']);$x++){
                                if ($driver_info['course']['training_materials'][$x]['this_training_materials_view_status']==0){
                                    $driver_info['test_status'] = 0;
                                    break;
                                }
                            }
                            if ($driver_info['order_num'] <= $driver_info['max_order_num']){
                                $driver_info['test_status'] = 0;
                            }
                        }
                    }
                }
            }

            $msg['data']['driver_info'] = $driver_info;
            if(!$driver) {
                $msg['data']['driver_info']['user_id'] = 0;
                $msg['data']['driver_info']['order_num'] = 0;
                $msg['data']['driver_info']['driver_rank_id'] = 0;
            }
            if (!$driver_rank){
                $msg['data']['driver_info']['rank_name'] = '新手';
                $msg['data']['driver_info']['min_order_num'] = 0;
                $msg['data']['driver_info']['max_order_num'] = 99999;
                $msg['data']['driver_info']['test_status'] = 0;
                $msg['data']['driver_info']['course'] = [];
            }



            //得到各个考卷的id
            for($i=0;$i<count($driver_train_list);$i++){
                $map['rank_id'] = $driver_train_list[$i]['id'];
                $map['user_id'] = $user_id;
                $map['ispass'] = true;
                $paper = DB::name('user_paper')
                    ->where($map)
                    ->find();
//                $msg['sql'][] = DB::name('user_paper')->getLastSql();
                $driver_train_list[$i]['score'] = $paper['score'];
                //判断司机是否通过考试
                if($paper['ispass']){
                    $driver_train_list[$i]['user_paper_exam_msg'] = '考试通过';
                    $driver_train_list[$i]['user_paper_exam_status'] = 1;
                }else{
                    $driver_train_list[$i]['user_paper_exam_msg'] = '考试未通过';
                    $driver_train_list[$i]['user_paper_exam_status'] = 0;
                }
                $driver_train_list[$i]['user_paper_id'] = $paper['id'];
            }


            //司机订单认证信息
            if ($driver_info['order_num'] >= $driver_info['max_order_num']){
                $driver_train_list[$i]['order_num_complete_msg'] = '已完成订单量';
                $driver_train_list[$i]['order_num_complete_status'] = 1;
            }else{
                $driver_train_list[$i]['order_num_complete_msg'] = '未完成订单量';
                $driver_train_list[$i]['order_num_complete_status'] = 0;
            }
//            for($i=0;$i<count($driver_train_list);$i++){
//                if($driver_rank['order_num']>=$driver_train_list[$i]['order_num']){
//                    $driver_train_list[$i]['order_num_complete_msg'] = '已完成订单量';
//                    $driver_train_list[$i]['order_num_complete_status'] = 1;
//                }else{
//                    $driver_train_list[$i]['order_num_complete_msg'] = '未完成订单量';
//                    $driver_train_list[$i]['order_num_complete_status'] = 0;
//                }
//                //$driver_train_list[$i]['order_info'] = $order_info;
//            }


            $msg['data']['rank_list'] =  $driver_train_list;

            if(!$msg){
                $msg['message'] = '失败';
                $msg['error_id'] = '1070007';
                return $this->error($msg);
            }else{
                $msg['message'] = '成功';
                return $this->success($msg);
            }

        }
   }
